﻿using System;
using System.Diagnostics;
using MyCompany.WebCrawler.Repositories;
using MyCompany.WebCrawler.Tasks;

namespace MyCompany.WebCrawler.Domain
{
    public class Crawler
    {
        private readonly TasksFactory factory;
        private readonly TaskQueue queue;
        private readonly IRepository repository;
        private ThreadManager manager;

        public Crawler(IRepository repository, TasksFactory factory, ThreadManager manager)
        {
            Trace.WriteLine("");
            Trace.WriteLine("");
            Trace.WriteLine("Init a crawler: " + DateTime.Now);
            Trace.WriteLine("Db: " + repository.Connection);

            this.repository = repository;
            this.factory = factory;
            this.queue = repository.Queue;
            this.manager = manager;

        }

        public void Run(string url)
        {
            Console.WriteLine("Run: " + DateTime.Now);
            Console.WriteLine("Url: " + url);

            Trace.WriteLine("Run: " + url);

            var task1 = factory.CreateGetLinks(url);
            var task2 = factory.CreateShowNewLinkTask();

            task1.Execute();
            task2.Execute();

            Trace.WriteLine("Done.");
        }

        public void RunMultithread(string url)
        {
            Console.WriteLine("Run: " + DateTime.Now);
            Console.WriteLine("Url: " + url);

            Trace.WriteLine("Run: " + url);

            queue.Enqueue(factory.CreateGetLinks(url));
            queue.Enqueue(factory.CreateShowNewLinkTask());

            int threads = 5;
            manager.Start(threads);

            Trace.WriteLine("Done.");
        }


    }
}
